import 'dart:convert';

import 'package:bruno/bruno.dart';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

import '../AppConfig/Config.dart';
import '../AppConfig/LocalStorage.dart';
import '../AppConfig/RouteAct.dart';
import '../Order/WaybillDetails/ModifyTransportationAgreement.dart';
import '../Order/WaybillDetails/NoInvoicingSpecified.dart';
import '../SendGoods/AddGoodsFirst.dart';
import '../http/NoLoadingGetApi.dart';
import '../http/api.dart';

class SelectSourceOfGoods extends StatefulWidget {
  const SelectSourceOfGoods({super.key, required this.carMap});
  final Map carMap;
  @override
  State<SelectSourceOfGoods> createState() => _SelectSourceOfGoodsState();
}

class _SelectSourceOfGoodsState extends State<SelectSourceOfGoods> {
  List dataList=[];
  int selectedRowIndex = -1;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getGoodsList(1);
    print(widget.carMap);
  }
  void getGoodsList(int current) async {
    String? shipperId=await UserIdManager.getUserID();
    NoLoadinggetApiManager.getData(
      context,
      "api/goods/goods/shipperOnlineGoodsPage",
      {"shipperId":shipperId,'current':current,"size":20,},
          (responseData)  {
        setState(() {
          dataList=responseData['data']['records'];

        });
      },
    );
  }
  @override
  Widget build(BuildContext context) {
    final screenSize = MediaQuery.of(context).size;
    return Scaffold(
      backgroundColor: MyColors.backgreyColor,
        appBar: AppBar(
        title:Text( "选择货源",style: TextStyle(fontWeight: FontWeight.w300,fontSize: 16.sp),),
        backgroundColor: Colors.white,
        centerTitle: true,
        ),
      floatingActionButton:Container(
        margin: EdgeInsets.only(right: 10.w,bottom:100.h),
        width: 110.w,
        height: 40.0,
        decoration: BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            colors: [Color.fromRGBO(231,112,27,0.85), Color.fromRGBO(239,160,82,1), Color.fromRGBO(239,160,82,1)], // 设置渐变颜色
          ),
          borderRadius: BorderRadius.circular(30.0), // 设置圆角
        ),
        child: FloatingActionButton(
          onPressed: () {
            Navigator.push( context, FadeRoute(page:AddGoodsFirst(
              dataMap: {}, editType: 1,
            )));
          },
          elevation: 0,
          backgroundColor: Colors.transparent,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(30.0), // 设置圆角
          ),
          child: Text('添加新货源', style: TextStyle(color: Colors.white,fontWeight: FontWeight.w600),
          ),
        ),

      ),
      body:Column(
        children: [
          Expanded(
            child:Container(
              margin: EdgeInsets.only(left: 10.w,right: 10.w),
              child: ListView.builder(
                  shrinkWrap:false,
                  itemCount:dataList.length,
                  itemBuilder: (BuildContext context, int index) {
                    return GestureDetector(
                      child:   Container(
                        padding: EdgeInsets.only(left: 16.w,top: 12.h,right: 11.h,bottom: 14.h),
                        decoration: BoxDecoration(
                            border: Border.all(
                              color: index == selectedRowIndex ?Color.fromRGBO(231, 112, 27, 0.85):Colors.white,  // 边框颜色
                              width: 1.0,          // 边框宽度
                            ),
                            color:index == selectedRowIndex ?Color.fromRGBO(251, 236, 228, 1): Colors.white,
                            borderRadius: BorderRadius.all(Radius.circular(10))),
                        margin: EdgeInsets.only(top: 8.h),
                        child: Column(
                          children: [
                            Row(
                              crossAxisAlignment: CrossAxisAlignment.center,
                              children: [

                                Column(
                                  children: [
                                    Image.asset("lib/Images/OrderList/装icon.png",
                                      width: 13.w, height: 13.h,),
                                    Image.asset(
                                      "lib/Images/OrderList/垂直虚线.png", width: 13.w,
                                      height: 15.h,),
                                    if(dataList[index]['loadPlaceInfo'].length == 2)
                                      Column(
                                        children: [
                                          Image.asset(
                                            "lib/Images/OrderList/装icon.png",
                                            width: 13.w, height: 13.h,),
                                          Image.asset(
                                            "lib/Images/OrderList/垂直虚线.png",
                                            width: 13.w, height: 15.h,),
                                        ],
                                      ),
                                    if( dataList[index]['unloadPlaceInfo'].length == 2)
                                      Column(
                                        children: [
                                          Image.asset(
                                            "lib/Images/OrderList/卸icon.png",
                                            width: 13.w, height: 13.h,),
                                          Image.asset(
                                            "lib/Images/OrderList/垂直虚线.png",
                                            width: 13.w, height: 15.h,),
                                        ],
                                      ),

                                    Image.asset("lib/Images/OrderList/卸icon.png",
                                      width: 13.w, height: 13.h,),
                                  ],
                                ),


                                Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    // SizedBox(height: 8.h,),
                                    Row(
                                      children: [
                                        Container(
                                          constraints: BoxConstraints(
                                            // minWidth: 60.w,
                                            maxWidth:screenSize.width/2.5, // 限制文本最大宽度
                                          ),
                                          child:  Text(
                                            dataList[index]["loadPlaceInfo"][0]["city"] +
                                                " " +
                                                dataList[index]["loadPlaceInfo"][0]["county"],
                                            style: TextStyle(
                                                color: Colors.black, fontSize: 13.sp,fontWeight: FontWeight.w600),overflow: TextOverflow.ellipsis,),
                                        ),

                                        SizedBox(width: 4.w,),
                                        Container(
                                          constraints: BoxConstraints(
                                            // minWidth: 60.w,
                                            maxWidth:screenSize.width/2.5, // 限制文本最大宽度
                                          ),
                                          child:  Text( dataList[index]["loadDay"]+" "+
                                            dataList[index]["loadTime"]+"点装货",
                                            style: TextStyle(color: Color.fromRGBO(
                                                154, 154, 154, 1), fontSize: 12.sp),overflow: TextOverflow.ellipsis,),
                                        ),
                                        if(dataList[index]['category'] == 1)
                                          BrnTagCustom(
                                            tagText: "企业",
                                            fontSize: 9.sp,
                                            backgroundColor: MyColors.themeColor,
                                            fontWeight: FontWeight.w600,
                                          ),
                                        if(dataList[index]['description'] == 1)
                                          BrnTagCustom(
                                            tagText: "专票",
                                            fontSize: 9.sp,
                                            fontWeight: FontWeight.w600,
                                          ),

                                      ],
                                    ),

                                    // Text(
                                    //   dataList[index]["loadPlaceInfo"][0]["address"],
                                    //   style: TextStyle(
                                    //       color: Color.fromRGBO(154, 154, 154, 1),
                                    //       fontSize: 12.sp),),
                                    SizedBox(height: 8.h,),
                                    if(dataList[index]["loadPlaceInfo"].length == 2)
                                      Column(
                                        crossAxisAlignment: CrossAxisAlignment.start,
                                        children: [
                                          Row(
                                            children: [
                                              Container(
                                                constraints: BoxConstraints(
                                                  // minWidth: 60.w,
                                                  maxWidth:screenSize.width/1.5, // 限制文本最大宽度
                                                ),
                                                child:  Text(
                                                  dataList[index]["loadPlaceInfo"][1]["city"] +
                                                      " " +
                                                      dataList[index]["loadPlaceInfo"][1]["county"],
                                                  style: TextStyle(color: Colors.black,
                                                      fontSize: 13.sp,fontWeight: FontWeight.w600),overflow: TextOverflow.ellipsis,),
                                              )

                                            ],
                                          ),
                                          // Text(
                                          //   dataList[index]["loadPlaceInfo"][1]["detailedAddress"],
                                          //   style: TextStyle(color: Color.fromRGBO(
                                          //       154, 154, 154, 1), fontSize: 12.sp),),
                                          SizedBox(height: 8.h,),
                                        ],
                                      ),

                                    Row(
                                      children: [
                                        Container(
                                          constraints: BoxConstraints(
                                            // minWidth: 60.w,
                                            maxWidth:screenSize.width/2.5,

                                        ),
                                          child:  Text(

                                            dataList[index]["unloadPlaceInfo"][0]["city"] +
                                                " " +
                                                dataList[index]["unloadPlaceInfo"][0]["county"],
                                            style: TextStyle(
                                                color: Colors.black, fontSize: 13.sp,fontWeight: FontWeight.w600),overflow: TextOverflow.ellipsis, ),
                                        ),

                                        SizedBox(width: 4.w,),

                                          if(dataList[index]["unloadTime"] !=null)
                                            Container(
                                              constraints: BoxConstraints(
                                                // minWidth: 60.w,
                                                maxWidth:screenSize.width/2.5,

                                              ),
                                              child:  Text(dataList[index]["unloadDay"]+" "+
                                                dataList[index]["unloadTime"]+"点卸货",overflow: TextOverflow.ellipsis,
                                                style: TextStyle(color: Color.fromRGBO(
                                                    154, 154, 154, 1), fontSize: 12.sp),),
                                            ),

                                      ],
                                    ),
                                    // Text(
                                    //   dataList[index]["unloadPlaceInfo"][0]["address"],
                                    //   style: TextStyle(color: Color.fromRGBO(
                                    //       154, 154, 154, 1), fontSize: 12.sp),),
                                    if(dataList[index]["unloadPlaceInfo"].length == 2)
                                      Column(
                                        crossAxisAlignment: CrossAxisAlignment.start,
                                        children: [
                                          SizedBox(height: 8.h,),
                                          Row(
                                            children: [

                                              Text(
                                                dataList[index]["unloadPlaceInfo"][1]["city"] +
                                                    " " +
                                                    dataList[index]["unloadPlaceInfo"][1]["county"],
                                                style: TextStyle(color: Colors.black,
                                                    fontSize: 13.sp,fontWeight: FontWeight.w600),),
                                              SizedBox(width: 4.w,),
                                              // Container(
                                              //   width: 140.w,
                                              //   child:  Text(dataList[index]["unloadDay"]+" "+
                                              //     dataList[index]["unloadTime"]+"点卸货",
                                              //     style: TextStyle(color: Color.fromRGBO(
                                              //         154, 154, 154, 1), fontSize: 12.sp),),
                                              // ),
                                            ],
                                          ),
                                          // Text(
                                          //   dataList[index]["unloadPlaceInfo"][1]["detailedAddress"],
                                          //   style: TextStyle(color: Color.fromRGBO(
                                          //       154, 154, 154, 1), fontSize: 12.sp),),

                                        ],
                                      ),

                                  ],

                                ),

                              ],
                            ),
                            SizedBox(height: 8.h,),
                            Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Row(
                                  crossAxisAlignment: CrossAxisAlignment.end,
                                  children: [
                                    if(dataList[index]["vehicleLength"].isNotEmpty)
                                      Text(dataList[index]["vehicleLength"].replaceAll(",", "/")+"米",style: TextStyle(color: Colors.black, fontSize: 13.sp),),
                                    Text("丨",style: TextStyle(color: Colors.black, fontSize: 13.sp),),
                                    if(dataList[index]["vehicleModel"].isNotEmpty)
                                      Text(dataList[index]["vehicleModel"],style: TextStyle(color: Colors.black, fontSize: 13.sp),),
                                    Text("丨",style: TextStyle(color: Colors.black, fontSize: 13.sp),),
                                    if(dataList[index]["cargoWeight"].isNotEmpty)
                                      Text(dataList[index]["cargoWeight"]+"吨,",style: TextStyle(color: Colors.black, fontSize: 13.sp),),
                                    if(dataList[index]["cargoVolume"].isNotEmpty)
                                      Text(dataList[index]["cargoVolume"]+"方",style: TextStyle(color: Colors.black, fontSize: 13.sp),),
                                    
                                  ],
                                ),
                                Row(
                                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                  children: [
                                    dataList[index]["freight"]!=0?
                                    Text((dataList[index]['freight']).toString()+"元/趟",style: TextStyle(color: MyColors.themeColor,fontSize: 16.sp),)
                                    :Text("电议",style: TextStyle(color: MyColors.themeColor,fontSize: 16.sp),),
                                    Text(dataList[index]["createTime"].substring(5, 16),
                                      style: TextStyle(color: MyColors.textColor, fontSize: 13.sp),),
                                  ],
                                )

                              ],
                            ),
                          ],
                        ),
                      ),
                      onTap: (){
                        setState(() {
                          selectedRowIndex = index;
                        });
                      },
                    );

                  } ),
          ) ,
          ),
          Container(
            padding: EdgeInsets.only(top: 10.h,right: 15.w,left: 15.w,bottom: 40.h),
            height: 85.h,
            color: Colors.white,
            child: BrnSmallMainButton(
              title: "确定",
              bgColor: MyColors.themeColor,
              textColor: Colors.white,
              fontWeight: FontWeight.w600,
              fontSize: 16.sp,
              width: screenSize.width-30.w,
              radius: 30,
              onTap: () {

                if(selectedRowIndex==-1){
                  BrnToast.show("请选择货源", context);
                }else {

                  showDialog(
                    barrierDismissible: false,
                    context: context,
                    builder: (BuildContext context) {
                      return BrnDialog(

                        titleText: "是否确认指派司机？",
                        actionsWidget: [
                          TextButton(
                            onPressed: () {
                             Navigator.pop(context);
                            },
                            child: Text("取消",style: TextStyle(color: MyColors.textColor,fontSize: 14.sp),),
                          ),
                          TextButton(

                            onPressed: () {
                              print(widget.carMap['driverId']);
                              ApiManager.postData(
                                context,
                                'api/waybill/shipper/waybill/add',
                                {
                                  "goodsId": dataList[selectedRowIndex]['id'],
                                  "driverId":widget.carMap['driverId'],
                                },
                                    (responseData) {
                                  BrnToast.show("指派成功", context);
                                  Navigator.pop(context);
                                  Navigator.pop(context);
                                  Navigator.pop(context);
                                },
                              );


                            },
                            child: Text("确定",style: TextStyle(color: MyColors.themeColor,fontSize: 14.sp),),
                          ),
                        ],
                      );
                    },
                  );


                }
              },
            ),
          ),
        ],
      ),
    );
  }
}
